package com.bjbn.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.bjbn.bean.SpHistoryVideoUrlParam;
import com.bjbn.bean.SpParam;
import com.bjbn.service.SPService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sp")
@Slf4j
public class SpController {
    @Autowired
    private SPService spService;

    @Value("${sp-config.base-url}")
    private String baseUrl;

    // 设备列表地址
    private final String treeListUrl = "VideoPlatform/Devices/getTreeList";

    // 视频播放地址
    private final String videoUrl = "VideoPlatform/VideoApi/getVideoUrls";

    // 楼层列表地址
    private final String floorUrl = "BasicManages/BasicFloor/getList";

    // 回放协议地址
    private final String historyVideoUrls = "VideoPlatform/VideoApi/getHistoryVideoUrls";

    // 控制地址
    private final String ptzUrl = "VideoPlatform/VideoApi/ptzforCamera";

    @RequestMapping("/login")
    public JSONObject login() {
        JSONObject jsonObject = new JSONObject();
        String token = spService.getSpToken();
        jsonObject.put("data", token);
        jsonObject.put("code", 200);
        jsonObject.put("success", true);
        return jsonObject;
    }

    /**
     * 获取设备列表
     *
     * @return
     */
    @RequestMapping("/getTreeList")
    public JSONObject getTreeList() {
        String url = baseUrl + treeListUrl;
        String authorization = "Bearer " + spService.getSpToken();

        HttpRequest request0 = HttpUtil
                .createGet(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization);
        HttpResponse response0 = request0.execute();
        log.info("Response Status: " + response0.getStatus());
        if (response0.getStatus() != 200) {
            return null;
        }

        JSONObject obj = JSONObject.parseObject(response0.body());

        if (obj.get("code") == "401") {
            // 如果返回401，是没有权限，重新获取一次token
            String token = spService.getSpTokenFocus();
            authorization = "Bearer " + token;
            HttpRequest request1 = HttpUtil
                    .createGet(url)
                    .setConnectionTimeout(5000)
                    .timeout(10000)
                    .header("Authorization", authorization);
            HttpResponse response1 = request1.execute();
            log.info("Response Status: " + response1.getStatus());

            if (response1.getStatus() != 200) {
                return null;
            }

            return JSONObject.parseObject(response1.body());

        } else {
            return obj;
        }
    }

    @RequestMapping("/getVideoUrls")
    public JSONObject getVideoUrls(@RequestBody SpParam param) {
        String url = baseUrl + videoUrl;
        String authorization = "Bearer " + spService.getSpToken();
        HttpRequest request0 = HttpUtil
                .createPost(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization)
                .header("Content-Type", "application/json")
                .body("{\"camera_id\":\"" + param.getCamera_id() + "\"}");
        HttpResponse response0 = request0.execute();
        //System.out.println("Response Status: " + response0.getStatus());
        //System.out.println("Response Body: " + response0.body());
        log.info("Response Status: " + response0.getStatus());
        if (response0.getStatus() != 200) {
            return null;
        }

        JSONObject obj = JSONObject.parseObject(response0.body());
        if (obj.get("code") == "401") {
            // 如果401是没有权限，重新获取一次token
            String token = spService.getSpTokenFocus();
            authorization = "Bearer " + token;
            HttpRequest request1 = HttpUtil
                    .createGet(url)
                    .setConnectionTimeout(5000)
                    .timeout(10000)
                    .header("Authorization", authorization);
            HttpResponse response1 = request1.execute();
            log.info("Response Status: " + response1.getStatus());

            if (response1.getStatus() != 200) {
                return null;
            }

            return JSONObject.parseObject(response1.body());

        } else {
            return obj;
        }
    }

    @RequestMapping("/getFloorList")
    public JSONObject getFloorList(int PageNum, int PageSize) {
        String url = baseUrl + floorUrl + "?PageNum=" + PageNum + "&PageSize=" + PageSize;
        String authorization = "Bearer " + spService.getSpToken();

        HttpRequest request0 = HttpUtil
                .createGet(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization);
        HttpResponse response0 = request0.execute();
        log.info("Response Status: " + response0.getStatus());
        if (response0.getStatus() != 200) {
            return null;
        }

        JSONObject obj = JSONObject.parseObject(response0.body());

        if (obj.get("code") == "401") {
            // 如果返回401，是没有权限，重新获取一次token
            String token = spService.getSpTokenFocus();
            authorization = "Bearer " + token;
            HttpRequest request1 = HttpUtil
                    .createGet(url)
                    .setConnectionTimeout(5000)
                    .timeout(10000)
                    .header("Authorization", authorization);
            HttpResponse response1 = request1.execute();
            log.info("Response Status: " + response1.getStatus());

            if (response1.getStatus() != 200) {
                return null;
            }

            return JSONObject.parseObject(response1.body());

        } else {
            return obj;
        }
    }

    @RequestMapping("/getHistoryVideoUrls")
    public JSONObject getHistoryVideoUrls(@RequestBody SpHistoryVideoUrlParam param) {
        String url = baseUrl + historyVideoUrls;
        String authorization = "Bearer " + spService.getSpToken();
        HttpRequest request0 = HttpUtil
                .createPost(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization)
                .header("Content-Type", "application/json")
                .body("{\"cameraid\":\"" + param.getCameraid() + "\",\"starttime\":\"" + param.getStarttime() + "\",\"stoptime\":\"" + param.getStoptime() + "\"}");

        System.out.println("getHistoryVideoUrls");
        System.out.println("{\"cameraid\":\"" + param.getCameraid() + "\",\"starttime\":\"" + param.getStarttime() + "\",\"stoptime\":\"" + param.getStoptime() + "\"}");
        HttpResponse response0 = request0.execute();
        System.out.println("Response Status: " + response0.getStatus());
        System.out.println("Response Body: " + response0.body());
        log.info("Response Status: " + response0.getStatus());
        if (response0.getStatus() != 200) {
            return null;
        }

        JSONObject obj = JSONObject.parseObject(response0.body());
        if (obj.get("code") == "401") {
            // 如果401是没有权限，重新获取一次token
            String token = spService.getSpTokenFocus();
            authorization = "Bearer " + token;
            HttpRequest request1 = HttpUtil
                    .createGet(url)
                    .setConnectionTimeout(5000)
                    .timeout(10000)
                    .header("Authorization", authorization);
            HttpResponse response1 = request1.execute();
            log.info("Response Status: " + response1.getStatus());

            if (response1.getStatus() != 200) {
                return null;
            }

            return JSONObject.parseObject(response1.body());

        } else {
            return obj;
        }
    }

    @RequestMapping("/ptzforCamera")
    public JSONObject ptzforCamera(String Camera_id, Integer Command, Integer Stopbit, Integer Speed, Integer LinkMode, Integer iswan) {
        String url = baseUrl + ptzUrl + "?Camera_id=" + Camera_id + "&Command=" + Command + "&Stopbit=" + Stopbit + "&Speed=" + Speed + "&LinkMode=" + LinkMode + "&iswan=" + iswan;
        String authorization = "Bearer " + spService.getSpToken();

        HttpRequest request0 = HttpUtil
                .createGet(url)
                .setConnectionTimeout(5000)
                .timeout(10000)
                .header("Authorization", authorization);
        HttpResponse response0 = request0.execute();
        log.info("Response Status: " + response0.getStatus());
        if (response0.getStatus() != 200) {
            return null;
        }

        JSONObject obj = JSONObject.parseObject(response0.body());

        if (obj.get("code") == "401") {
            // 如果返回401，是没有权限，重新获取一次token
            String token = spService.getSpTokenFocus();
            authorization = "Bearer " + token;
            HttpRequest request1 = HttpUtil
                    .createGet(url)
                    .setConnectionTimeout(5000)
                    .timeout(10000)
                    .header("Authorization", authorization);
            HttpResponse response1 = request1.execute();
            log.info("Response Status: " + response1.getStatus());

            if (response1.getStatus() != 200) {
                return null;
            }

            return JSONObject.parseObject(response1.body());

        } else {
            return obj;
        }
    }
}
